package ${beanPackage};

import co.paralleluniverse.fibers.Suspendable;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.SQLConnection;
import ldh.common.PageResult;
import ${projectPackage}.dao.${table.javaName}Dao;
import ${projectPackage}.util.BeanUtil;
import ${projectPackage}.util.JsonObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import static io.vertx.ext.sync.Sync.awaitResult;

/**
 * Created by ldh123 on 2018/6/23.
 */
public class ${table.javaName}Service extends JdbcService {

    private static final Logger logger = LoggerFactory.getLogger(${className}.class);

    private ${table.javaName}Dao ${util.firstLower(table.javaName)}Dao = BeanUtil.getBean(${table.javaName}Dao.class);;

    @Suspendable
    public void save(JDBCClient jdbcClient, JsonObject jsonObject) {
        transaction(jdbcClient, conn->{
            if (jsonObject.containsKey("${util.firstLower(table.primaryKey.column.name)}")) {
                ${util.firstLower(table.javaName)}Dao.update(conn, jsonObject);
            } else {
                ${util.firstLower(table.javaName)}Dao.insert(conn, jsonObject);
            }
            return null;
        });
    }

    @Suspendable
    public PageResult<JsonObject> list(JDBCClient jdbcClient, JsonObject jsonObject) {
        try (SQLConnection conn = awaitResult(jdbcClient::getConnection)) {
            long total = ${util.firstLower(table.javaName)}Dao.count(conn, jsonObject);
            List<JsonObject> datas = new ArrayList<>();
            if (total > 0) {
                datas = ${util.firstLower(table.javaName)}Dao.list(conn, jsonObject);
            }
            PageResult pageResult = new PageResult<JsonObject>(total, datas);
            JsonObjectUtil.pageable(pageResult, jsonObject);
            return pageResult;
        }
    }

    @Suspendable
    public JsonObject getById(JDBCClient jdbcClient, JsonObject jsonObject) {
        return query(jdbcClient, conn->{
            return ${util.firstLower(table.javaName)}Dao.getById(conn, jsonObject);
        });
    }
}
